import os
from datetime import datetime
from flask import render_template, redirect, url_for, flash, request, current_app
from flask_login import login_required, current_user
from werkzeug.utils import secure_filename
from extensions import db
from . import main_bp_zc
from .models import ProfileSection_zc, HeroImage_zc, Post_zc
from .forms import PostForm

def allowed_file(filename):
    """检查文件类型是否允许"""
    ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@main_bp_zc.route('/')
def index():
    """首页"""
    # 获取轮播图
    hero_images = HeroImage_zc.query.filter_by(is_enabled=True).order_by(HeroImage_zc.display_sequence).all()
    
    # 获取最新动态
    posts = Post_zc.query.order_by(Post_zc.created_at.desc()).limit(10).all()
    
    return render_template('main/index.html', hero_images=hero_images, posts=posts)

@main_bp_zc.route('/profile/<nickname>')
def profile(nickname):
    """个人主页"""
    # 获取所有版块
    sections = ProfileSection_zc.query.order_by(ProfileSection_zc.sort_order).all()
    return render_template('main/profile.html', sections=sections)

@main_bp_zc.route('/post/new', methods=['GET', 'POST'])
@login_required
def new_post():
    """发布新动态"""
    form = PostForm()
    if form.validate_on_submit():
        post = Post_zc(
            user_id=current_user.id,
            content=form.content.data
        )
        
        # 处理图片上传
        if form.image.data:
            filename = secure_filename(form.image.data.filename)
            # 生成唯一的文件名
            unique_filename = f"{current_user.id}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}_{filename}"
            # 确保上传目录存在
            upload_folder = os.path.join(current_app.config['UPLOAD_FOLDER'], 'posts')
            os.makedirs(upload_folder, exist_ok=True)
            # 保存文件
            file_path = os.path.join(upload_folder, unique_filename)
            form.image.data.save(file_path)
            # 保存相对路径到数据库
            post.image_url = f"/static/uploads/posts/{unique_filename}"
        
        db.session.add(post)
        db.session.commit()
        flash('动态发布成功', 'success')
        return redirect(url_for('main_bp_zc.index'))
    return render_template('main/new_post.html', form=form)

@main_bp_zc.route('/post/<int:id>')
def view_post(id):
    """查看动态详情"""
    post = Post_zc.query.get_or_404(id)
    return render_template('main/post.html', post=post)

@main_bp_zc.route('/post/<int:id>/delete', methods=['POST'])
@login_required
def delete_post(id):
    """删除动态"""
    post = Post_zc.query.get_or_404(id)
    if post.user_id != current_user.id:
        flash('您没有权限删除此动态', 'danger')
        return redirect(url_for('main_bp_zc.index'))
    
    # 删除关联的图片文件
    if post.image_url:
        try:
            image_path = os.path.join(current_app.root_path, post.image_url.lstrip('/'))
            if os.path.exists(image_path):
                os.remove(image_path)
        except Exception as e:
            current_app.logger.error(f"删除图片文件失败: {str(e)}")
    
    db.session.delete(post)
    db.session.commit()
    flash('动态已删除', 'success')
    return redirect(url_for('main_bp_zc.index')) 